package com.guuyoog.mooncommon.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Guy
 * @date 2018/07/30 16:25
 */
public class QrCodeUtil {

    /**
     * 生成二维码
     */
    private static void createQrCode() {
        int width = 300;
        int height = 300;
        String format = "png";
        String content = "www.baidu.com";
        //定义二维码的参数
        Map<EncodeHintType, Object> map = new HashMap<>(16);
        //设置编码
        map.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        //设置纠错等级
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        map.put(EncodeHintType.MARGIN, 2);

        try {
            //生成二维码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, map);
            Path file = new File("E:/qrcode.png").toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, format, file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取二维码
     */
    private static void readQrCode() {
        try {
            MultiFormatReader multiFormatReader = new MultiFormatReader();
            File file = new File("E:/qrcode.png");
            BufferedImage image = ImageIO.read(file);
            //定义二维码参数
            Map<DecodeHintType, Object> hints = new HashMap<>(16);
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");

            //获取读取二维码结果
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
            Result result = multiFormatReader.decode(binaryBitmap, hints);

            System.out.println("读取二维码： " + result.toString());
            System.out.println("二维码格式： " + result.getBarcodeFormat());
            System.out.println("二维码内容： " + result.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        QrCodeUtil.createQrCode();
        QrCodeUtil.readQrCode();
    }

}
